"""
步骤执行记录模型
"""
from datetime import datetime
from ..models.base import db
import json

class StepExecutionRecord(db.Model):
    """步骤执行记录表"""
    id = db.Column(db.Integer, primary_key=True)
    execution_id = db.Column(db.Integer, db.ForeignKey('execution_record.id'), nullable=False)
    step_id = db.Column(db.Integer)  # 对应SceneStep的ID
    step_name = db.Column(db.String(100))
    step_type = db.Column(db.String(20))
    status = db.Column(db.String(20))  # SUCCESS, FAILED
    start_time = db.Column(db.DateTime, default=datetime.now)
    end_time = db.Column(db.DateTime)
    request = db.Column(db.Text)  # 请求内容，JSON格式
    response = db.Column(db.Text)  # 响应内容，JSON格式
    error = db.Column(db.Text)  # 错误信息
    
    # 关系
    execution = db.relationship('ExecutionRecord', back_populates='step_records')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'execution_id': self.execution_id,
            'step_id': self.step_id,
            'step_name': self.step_name,
            'step_type': self.step_type,
            'status': self.status,
            'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': self.end_time.strftime('%Y-%m-%d %H:%M:%S') if self.end_time else None,
            'request': json.loads(self.request) if self.request else {},
            'response': json.loads(self.response) if self.response else {},
            'error': self.error
        }